load("@rules_cc//cc:defs.bzl", "cc_library")

package(default_visibility = ["//visibility:public"])

_DEFINES = [
    # https://github.com/libfuse/libfuse/blob/fuse-3.16.2/meson.build#L77
    "_REENTRANT",
    "HAVE_LIBFUSE_PRIVATE_CONFIG_H",
    "_FILE_OFFSET_BITS=64",
] + [
    # https://github.com/libfuse/libfuse/blob/fuse-3.16.2/lib/meson.build#L36
    "FUSE_USE_VERSION=316",
    'FUSERMOUNT_DIR=\\"/usr/bin\\"',
]

cc_library(
    name = "libfuse",
    srcs = [
        "lib/buffer.c",
        "lib/compat.c",
        "lib/cuse_lowlevel.c",
        "lib/fuse.c",
        "lib/fuse_i.h",
        "lib/fuse_log.c",
        "lib/fuse_loop.c",
        "lib/fuse_loop_mt.c",
        "lib/fuse_lowlevel.c",
        "lib/fuse_misc.h",
        "lib/fuse_opt.c",
        "lib/fuse_signals.c",
        "lib/helper.c",
        "lib/modules/iconv.c",
        "lib/modules/subdir.c",
        "lib/mount.c",
        "lib/mount_util.c",
        "lib/mount_util.h",
    ],
    hdrs = [
        "include/cuse_lowlevel.h",
        "include/fuse.h",
        "include/fuse_common.h",
        "include/fuse_kernel.h",
        "include/fuse_log.h",
        "include/fuse_lowlevel.h",
        "include/fuse_mount_compat.h",
        "include/fuse_opt.h",
    ],
    includes = ["include"],
    local_defines = _DEFINES,
    deps = [":config"],
)

cc_library(
    name = "config",
    hdrs = [
        "config/fuse_config.h",
        "config/libfuse_config.h",
    ],
    includes = ["config"],
)

genrule(
    name = "fuse_config",
    srcs = [],
    outs = ["config/fuse_config.h"],
    cmd = """cat > $@ << EOF
#pragma once
#define HAVE_COPY_FILE_RANGE
#define HAVE_FALLOCATE
#define HAVE_FDATASYNC
#define HAVE_FORK
#define HAVE_FSTATAT
#define HAVE_ICONV
#define HAVE_OPENAT
#define HAVE_PIPE2
#define HAVE_POSIX_FALLOCATE
#define HAVE_READLINKAT
#define HAVE_SETXATTR
#define HAVE_SPLICE
#define HAVE_STRUCT_STAT_ST_ATIM
#undef HAVE_STRUCT_STAT_ST_ATIMESPEC
#define HAVE_UTIMENSAT
#define HAVE_VMSPLICE
#define PACKAGE_VERSION "{}"
EOF""".format(module_version()),
)

genrule(
    name = "libfuse_config",
    srcs = [],
    outs = ["config/libfuse_config.h"],
    cmd = """cat > $@ << EOF
#pragma once
#define LIBFUSE_BUILT_WITH_VERSIONED_SYMBOLS 1
EOF""",
)
